package com.zhixi.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class UploadUtil {

    /**
     * 阿里域名
     */
    public static String TO_BIND_DOMAIN;

    /**
     * 地域节点
     */
    public static String END_POINT;
    /**
     * 存储桶名称
     */
    private static String BUCKET;

    /**
     * 阿里账户
     */
    public static String ACCESS_KEY;
    public static String ACCESS_KEY_SECRET;

    @Value("${aliyun.oss.tobinddoman}")
    public void setToBindDomain(String toBindDomain) {
        TO_BIND_DOMAIN = toBindDomain;
    }

    @Value("${aliyun.oss.endpoint}")
    public void setEndPoint(String endPoint) {
        END_POINT = endPoint;
    }

    @Value("${aliyun.accessKeyId}")
    public void setAccessKey(String accessKey) {
        ACCESS_KEY = accessKey;
    }

    @Value("${aliyun.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        ACCESS_KEY_SECRET = accessKeySecret;
    }

    @Value("${aliyun.oss.bucket}")
    public void setBucket(String bucket) {
        BUCKET = bucket;
    }

    public static String uploadImage(MultipartFile file) throws IOException {
        //生成文件名
        String originalFilename = file.getOriginalFilename();
        //原来的图片名
        String ext = "." + FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;
        //OSS客户端对象,需要传入地域节点，阿里云账号的key和value
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY, ACCESS_KEY_SECRET);
        ossClient.putObject(BUCKET, fileName, file.getInputStream());
        ossClient.shutdown();
        return TO_BIND_DOMAIN + fileName;
    }
}
